'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const { INTEGER, DECIMAL, STRING, TEXT, ENUM, DATE } = Sequelize;
    
    await queryInterface.createTable('products', {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      sku: {
        type: STRING(100),
        allowNull: false,
        unique: true,
        comment: '产品SKU'
      },
      name: {
        type: STRING(200),
        allowNull: false,
        comment: '产品名称'
      },
      specification: {
        type: STRING(500),
        comment: '产品规格'
      },
      unit: {
        type: STRING(50),
        comment: '单位'
      },
      category_id: {
        type: INTEGER,
        allowNull: true,
        comment: '产品类目ID'
      },
      brand: {
        type: STRING(100),
        comment: '品牌'
      },
      description: {
        type: TEXT,
        comment: '产品描述'
      },
      stock: {
        type: INTEGER,
        defaultValue: 0,
        comment: '当前库存'
      },
      min_stock: {
        type: INTEGER,
        defaultValue: 0,
        comment: '安全库存'
      },
      sale_price: {
        type: DECIMAL(10, 2),
        defaultValue: 0,
        comment: '售价'
      },
      cost_price: {
        type: DECIMAL(10, 2),
        defaultValue: 0,
        comment: '成本价'
      },
      status: {
        type: ENUM('active', 'inactive', 'outofstock'),
        defaultValue: 'active',
        comment: '产品状态: active-在售, inactive-下架, outofstock-缺货'
      },
      created_at: {
        type: DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        type: DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    });
    
    // 添加索引
    await queryInterface.addIndex('products', ['sku'], {
      name: 'products_idx_sku',
      unique: false
    });
    await queryInterface.addIndex('products', ['name'], {
      name: 'products_idx_name',
      unique: false
    });
    await queryInterface.addIndex('products', ['category_id'], {
      name: 'products_idx_category',
      unique: false
    });
    await queryInterface.addIndex('products', ['status'], {
      name: 'products_idx_status',
      unique: false
    });
    await queryInterface.addIndex('products', ['brand'], {
      name: 'products_idx_brand',
      unique: false
    });
  },

  down: async (queryInterface, Sequelize) => {
    // 删除索引
    await queryInterface.removeIndex('products', 'products_idx_sku');
    await queryInterface.removeIndex('products', 'products_idx_name');
    await queryInterface.removeIndex('products', 'products_idx_category');
    await queryInterface.removeIndex('products', 'products_idx_status');
    await queryInterface.removeIndex('products', 'products_idx_brand');
    
    await queryInterface.dropTable('products');
  }
};